package com.invengo.module_check.ui.fragment.netmodel;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.TimeUtils;
import com.invengo.module_check.BR;
import com.invengo.module_check.R;
import com.invengo.module_check.data.entity.BundleKey;
import com.invengo.module_check.databinding.FragmentNetModelBinding;
import com.invengo.module_check.ui.activity.main.MainActivity;

import java.text.SimpleDateFormat;
import java.util.Date;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.MaterialDialogUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class NetModelFragment extends BaseFragment<FragmentNetModelBinding, NetModelViewModel> {
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_net_model;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    MaterialDialog downloadDiaog, conformDialog, datePickerDialog;

    @Override
    public void initViewObservable() {
        viewModel.uc.downloadDialogEvent.observe(this, aBoolean -> {
            if (downloadDiaog == null) initDownloadDialog();
            if (aBoolean) {
                downloadDiaog.setProgress(0);
                downloadDiaog.show();
            } else
                downloadDiaog.dismiss();
        });

        viewModel.uc.downloadProgressEvent.observe(this, integer -> {
            if (downloadDiaog != null && downloadDiaog.isShowing())
                if (integer == -1) {
                    downloadDiaog.setProgress(0);
                } else {
                    downloadDiaog.incrementProgress(integer);
                }
        });
        viewModel.uc.dateDialogEvent.observe(this, dateTime -> {
            if (datePickerDialog == null)
                initDateDialog();
            setDefaultTime(dateTime);
            if (!datePickerDialog.isShowing())
                datePickerDialog.show();
        });

        viewModel.uc.downloadContentEvent.observe(this, str -> {
            if (downloadDiaog != null && downloadDiaog.isShowing())
                downloadDiaog.setContent(str);
        });

        viewModel.uc.conformDialogEvent.observe(this, title -> {
            if (conformDialog == null)
                initConformDialog();
            conformDialog = conformDialog.getBuilder().content("该操作将会" + title + "，请确认...").build();
            if (!conformDialog.isShowing())
                conformDialog.show();
        });
    }

    private void initDownloadDialog() {
        downloadDiaog = new MaterialDialog.Builder(getActivity())
                .title("数据下载中")
                .cancelable(false)
                .content("正在获取图书数据...")
                .contentGravity(GravityEnum.CENTER)
                .progress(false, 100, true)
                .build();
    }

    private String time;
    DatePicker datePicker;

    private void initDateDialog() {
        if (datePickerDialog == null) {
            datePickerDialog = new MaterialDialog.Builder(getActivity())
                    .title("日期选择")
                    .customView(R.layout.dialog_datepicker, false)
                    .positiveText("确定")
                    .negativeText("全局下载")
                    .negativeColorRes(R.color.color_red)
                    .onNegative((dialog, which) -> {
                        viewModel.changeDate("");
                    })
                    .onPositive((dialog, which) -> {
                        if (TimeUtils.string2Millis(time + " 00:00:00") - System.currentTimeMillis() < 0) {
                            viewModel.changeDate(time);
                        } else {
                            ToastUtils.showShort("不能选择比当前时间大的日期");
                        }
                    })
                    .build();
            datePicker = datePickerDialog.getCustomView().findViewById(R.id.datePicker);
        }
    }

    private void setDefaultTime(String dateTime){
        if (TextUtils.isEmpty(dateTime)) {
            dateTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
            time = dateTime;
        }
        String[] date = dateTime.split("-");
        datePicker.init(Integer.valueOf(date[0]), Integer.valueOf(date[1]) - 1, Integer.valueOf(date[2]),
                (view, year, monthOfYear, dayOfMonth) -> {
                    time = String.format("%s-%s-%s", year, monthOfYear + 1, dayOfMonth);
                });
    }

    private void initConformDialog() {
        conformDialog = MaterialDialogUtils.showBasicDialog(getActivity(), "温馨提示！")
                .contentGravity(GravityEnum.CENTER)
                .negativeText("取消")
                .onNegative((dialog, which) -> {
                    dialog.dismiss();
                })
                .positiveText("确定")
                .onPositive((dialog, which) -> {
                    dialog.dismiss();
                    viewModel.conformOpeartion();
                })
                .build();
    }

    @Override
    public void onError(String errorInfo) {
        if (downloadDiaog != null) {
            downloadDiaog.dismiss();
        }
    }
}
